﻿using System;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using Newtonsoft.Json;

namespace BellAssistant.Common.CommonHelper
{
    public class APIHelper
    {
        public static Task<object> GetJsonData(string url, object obj)
        {
            Task<object> json = null;
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.Timeout = 1000 * 600;
                request.ReadWriteTimeout = 1000 * 600;
                request.Method = "post";
                request.Proxy = null;
                request.ContentType = "application/json; charset=utf-8";
                string jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
                Encoding encoding = Encoding.UTF8;
                byte[] buffer = encoding.GetBytes(jsonStr);
                request.ContentLength = buffer.Length;
                request.GetRequestStream().Write(buffer, 0, buffer.Length);
                //HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                HttpWebResponse response;
                try
                {
                    response = (HttpWebResponse)request.GetResponse();
                }
                catch (WebException ex)
                {
                    LogHelper.WriteLog.Error("WebException :" + ex.Message, ex);
                    response = (HttpWebResponse)ex.Response;
                }
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
                {
                    string strResult = reader.ReadToEnd();
                    var result = JsonConvert.DeserializeObjectAsync(strResult);
                    json = result;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog.Error(ex.Message, ex);
                json = null;
            }
            return json;
        }
    }
}
